<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="merchantId">
        <el-select v-model="queryParams.merchantId" style="width: 100px;" placeholder="选择商户"
                   @keyup.enter.native="handleQuery" @change="handleChange">
          <el-option key="" value="" label="独立店铺"></el-option>
          <el-option v-for="mer in merchantList"
                     :key="mer.merchantId"
                     :label="mer.defindName ? mer.defindName : mer.merchantName"
                     :value="mer.merchantId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="shopId">
        <el-select v-model="queryParams.shopId" style="width: 100px;" placeholder="选择店铺"
                   @keyup.enter.native="handleQuery">
          <el-option v-for="shop in shopList"
                     :key="shop.shopId"
                     :label="shop.defindName ? shop.defindName : shop.shopName"
                     :value="shop.shopId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="buyerUsername">
        <el-input v-model="queryParams.buyerUsername" style="width: 120px;" placeholder="买家用户名" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item prop="orderSn">
        <el-input v-model="queryParams.orderSn" style="width: 180px;" placeholder="订单编号" clearable
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item prop="region">
        <el-select v-model="queryParams.region" style="width: 115px;" placeholder="请选择地区"
                   @keyup.enter.native="handleQuery">
          <el-option v-for="region in regionOptions"
                     :key="region.region"
                     :label="region.name"
                     :value="region.region"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="orderStatus">
        <el-select v-model="queryParams.orderStatus" style="width: 115px;" placeholder="请选择状态"
                   @keyup.enter.native="handleQuery" clearable>
          <el-option v-for="(label, status) in statusOptions"
                     :key="status"
                     :label="label"
                     :value="status"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">刷新</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" :disabled="multiple" size="mini" @click="handlePrintOrder">
          打印
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div class="order-contain" @contextmenu.prevent>
      <el-table stripe border v-loading="loading" :data="tableData" ref="dataTable"
                @row-click="handleRowClick"
                @row-contextmenu="handleRowAction"
                @contextmenu.native="showContextMenu"
                :row-class-name="highlightRow"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" align="center"/>
        <el-table-column label="订单编号" prop="orderSn" align="center"/>
        <el-table-column label="产品" align="center" width="350">
          <template slot-scope="scope">
            <div class="item-cell">
              <ul>
                <li v-for="(item, index) in scope.row.itemList" class="item-cell-li">
                  <el-popover width="300" trigger="hover" placement="top">
                    <el-image :src="transformedImageUrl(item.image_info.image_url)"/>
                    <div slot="reference">
                      <a :href="getProductUrl(scope.row.region) + '/product/'+ scope.row.shopId +'/'+ + item.item_id"
                         target="_blank">
                        <el-image :src="transformedImageUrl(item.image_info.image_url)" class="item-image"/>
                      </a>
                    </div>
                  </el-popover>
                  <p v-if="index === 0">
                    <span>收入：</span>
                    <span class="text-bold">{{ scope.row.totalAmount }}</span>
                    <span>&nbsp;元</span>
                  </p>
                  <p>成本：{{ item.item_sku }}元</p>
                  <p>型号：{{ item.model_name }} × <span class="text-bold">{{item.model_quantity_purchased}}</span></p>
                </li>
              </ul>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="备注" align="left">
          <template slot-scope="scope">
            <div>
              <p v-if="scope.row.messageToSeller">
                <el-tag size="mini" type="success">客户</el-tag>
                &nbsp;:&nbsp;{{ scope.row.messageToSeller }}
              </p>
              <p v-if="scope.row.sysNote">
                <el-tag size="mini">仓库</el-tag>
                &nbsp;:&nbsp;{{ scope.row.sysNote }}
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="买家信息" align="left">
          <template slot-scope="scope">
            <div class="user-cell">
              <p>
                <el-tag size="mini" type="info">{{ getRegionName(scope.row.region) }}</el-tag>
                &nbsp;
                <el-tag v-if="scope.row.cod" size="small" type="warning">货到付款</el-tag>
                &nbsp;
                <el-tag v-if="!scope.row.merchantId" size="small" type="danger">本土</el-tag>
              </p>
              <p>
                <el-tag size="mini" type="info">{{ scope.row.shopName }}</el-tag>
              </p>
              <!--           style="color: red"       <p>ID:{{ scope.row.buyerUserId }}</p>-->
              <p><i class="el-icon-s-custom"/>&nbsp;{{ scope.row.buyerUsername }} &nbsp;<el-tag
                v-if="scope.row.black" size="mini" type="danger">黑名单
              </el-tag>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="时间" align="left">
          <template slot-scope="scope">
            <div class="time-cell">
              <p>下单：{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}") }}</p>
              <p v-if="scope.row.payTime">付款：{{ parseTime(scope.row.payTime, "{y}-{m}-{d} {h}:{i}") }}</p>
              <p v-if="scope.row.sysStatus">
                <el-tag size="mini" type="info">发货剩余</el-tag>&nbsp;
                <span v-if="isIn48Hours(scope.row.shipByDate)"
                      class="text-bold text-danger">{{ formatTimeDifference(scope.row.shipByDate) }}</span>
                <span v-else class="text-bold">{{ formatTimeDifference(scope.row.shipByDate) }}</span>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">
            <div class="user-cell">
              <p>
                <el-tag
                  v-if="scope.row.orderStatus ==='IN_CANCEL'|| scope.row.orderStatus ==='TO_RETURN'"
                  size="small" type="danger">{{ statusOptions[scope.row.orderStatus] }}
                </el-tag>
                <el-tag v-else size="small" type="info">{{ statusOptions[scope.row.orderStatus] }}</el-tag>
              </p>
              <p>
                <el-tag v-if="scope.row.emergency" size="small" type="danger">加急</el-tag>
              </p>
              <p>
                <el-tag v-if="[-1].includes(scope.row.sysStatus)" size="small" type="danger">
                  {{ sysStatusOptions[scope.row.sysStatus] }}
                </el-tag>
                <el-tag
                  v-else-if="[3,5,6].includes(scope.row.sysStatus)"
                  size="small" type="success">
                  {{ sysStatusOptions[scope.row.sysStatus] }}
                </el-tag>
                <el-tag v-else-if="[1,2,4].includes(scope.row.sysStatus)" size="small" type="info">
                  {{ sysStatusOptions[scope.row.sysStatus] }}
                </el-tag>
              </p>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作记录" align="left">
          <template slot-scope="scope">
            <div class="time-cell">
              <p v-for="record in scope.row.records">{{
                  parseTime(record.createTime, "{m}-{d} {h}:{i}")
                }}:{{ record.createBy }}{{ record.type }}&nbsp;{{ record.detail }}</p>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>
    <!--右键内容-->
    <ContextMenu v-if="isContextMenuVisible" :position="contextMenuPosition" :row="contextMenuRow" ref="contextMenu"
                 @context-menu-action="handleContextMenuAction"/>
    <!-- 添加或修改打包订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="22">
            <el-form-item label="备注" prop="sysNote">
              <el-input type="textarea" :rows="10" v-model="form.sysNote" placeholder="请填写备注"/>
              <el-input v-show="false" v-model="form.sysStatus"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import ContextMenu from "@/components/OrderContextMenu";
import {listAllMerchant} from "@/api/shop/merchant";
import {listAllLoaclShop} from "@/api/shop/shop";
import {
  purchaseOrder,
  submitOrder,
  finishOrder,
  outsOrder,
  outOrder,
  emergencyOrder,
  remarkOrder,
  blackOrder,
} from "@/api/order/pack";
import {
  getOrder,
  listAllSupplier,
  listOrder,
  printOrder,
  syncOrder,
} from "@/api/order/order";
import Cookies from "js-cookie";

export default {
  name: "PriceConfig",
  components: {
    ContextMenu,
  },
  data() {
    return {
      statusOptions: {
        'UNPAID': '订单未支付',
        'READY_TO_SHIP': '订单待发货',
        'PROCESSED': '卖家已经操作发货',
        'RETRY_SHIP': '3PL揽收失败，需要重新发货',
        'SHIPPED': '3PL揽收成功',
        'TO_CONFIRM_RECEIVE': '等待买家确认签收',
        'IN_CANCEL': '买家提交取消申请待处理',
        'CANCELLED': '订单已取消',
        'TO_RETURN': '买家提交退货申请待处理',
        'COMPLETED': '订单已完成',
      },
      regionOptions: [
        {region: "TW", name: "台湾", uri: "https://xiapi.xiapibuy.com"},
        {region: "VN", name: "越南", uri: "https://vn.xiapibuy.com"},
        {region: "SG", name: "新加坡", uri: "https://sg.xiapibuy.com"},
        {region: "ID", name: "印尼", uri: "https://id.xiapibuy.com"},
        {region: "BR", name: "巴西", uri: "https://br.xiapibuy.com"},
        {region: "MX", name: "墨西哥", uri: "https://mx.xiapibuy.com"},
        {region: "CO", name: "哥伦比亚", uri: "https://co.xiapibuy.com"},
        {region: "CL", name: "智利", uri: "https://cl.xiapibuy.com"},
        {region: "PH", name: "菲律宾", uri: "https://ph.xiapibuy.com"},
        {region: "TH", name: "泰国", uri: "https://th.xiapibuy.com"},
        {region: "MY", name: "马来", uri: "https://my.xiapibuy.com"},
      ],
      sysStatusOptions: {
        1: '未采购',
        2: '已采购',
        3: '已发货',
        4: '缺货',
        5: '未知',
        6: '已完成',
        '-1': '取消/退货',
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      //全球商户列表
      merchantList: [],
      //店铺列表
      shopList: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 打包订单表格数据
      tableData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {

        pageNum: 1,
        pageSize: 50,
        merchantId: null,
        region: null,
        orderStatus: null,
        shopId: null,
        orderSn: null,
        buyerUsername: null,
        sysStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      //供应商列表
      supplierList: [],
      //顶部选择的值
      //topSelectValue: 1,
      //右键的值
      isContextMenuVisible: false,
      contextMenuPosition: {x: 0, y: 0},
      contextMenuRow: null,
      //是否固定顶部
      isOrderTopFixed: false,
      //是否操作缺货
      isOut: false,
    };
  },
  created() {
    this.getList();
    this.getMerchantList();
    this.getSupplierList();
  },
  methods: {
    //获取商品链接
    getProductUrl(reg) {
      return this.regionOptions.find((r) => r.region === reg).uri;
    },
    getRegionName(reg) {
      return this.regionOptions.find((r) => r.region === reg).name;
    },
    //替换图片链接
    transformedImageUrl(val) {
      // 使用正则表达式匹配'/file/'之后的部分，然后进行替换
      return val.replace(/.*\/file\//, 'https://s-cf-tw.shopeesz.com/file/');
    },
    //处理同步
    handleSync() {
      this.$modal.confirm('同步耗时2分钟左右，请2分钟之后再操作本系统').then(function () {
        return syncOrder();
      }).then(() => {
        this.$modal.msgSuccess("同步成功！");
      }).catch(() => {
      });
    },
    //采购
    handlePurchase(supplierId) {
      purchaseOrder(this.ids, {supplierId}).then((response) => {
        this.$modal.msgSuccess("采购成功！");
        this.getList();
      });
    },

    /** 查询打包订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    getMerchantList() {
      listAllMerchant().then((response) => {
        this.merchantList = response.data;
      });
    },

    //获取供应商
    getSupplierList() {
      listAllSupplier().then((response) => {
        this.supplierList = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        orderSn: null,
        sysNote: null,
        sysStatus: null,
      };
      this.resetForm("form");
    },
    //级联下拉框
    handleChange(val) {
      this.shopList = [];
      this.queryParams.shopId = null;
      //修改店铺的下拉框
      listAllLoaclShop({merchantId: val}).then((response) => {
        this.shopList = response.data;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.loading = true;
      listOrder(this.queryParams).then((response) => {
        this.tableData = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.orderSn);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },

    //打印
    handlePrintOrder() {
      this.openPrintPdf(this.ids);
    },

    //打开新页面并展示PDF
    openPrintPdf(sns) {
      this.loading = true;
      printOrder(sns).then(response => {
        this.loading = false;
        if (response.msg) {
          window.open(response.msg, '_blank');
        }else {
          this.$modal.msgError("订单无法打印");
        }
      });
    },

    // 加急操作
    handleUrgent(row) {
      emergencyOrder({orderSn: row.orderSn, emergency: !row.emergency}).then((response) => {
        this.$modal.msgSuccess(row.emergency ? "取消加急成功！" : "加急成功！");
        row.emergency = !row.emergency;
      });
    },
    //处理备注操作
    handleNote(row) {
      this.reset();
      const orderSn = row.orderSn || this.ids;
      getOrder(orderSn).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "添加备注";
        this.isOut = false;
      });
    },
    //处理拉黑
    handleBlack(row) {
      this.$modal.confirm('是否要拉黑' + row.buyerUsername + '用户？')
        .then(() => {
          //拉黑
          blackOrder({orderSn: row.orderSn, black: !row.black}).then((response) => {
            this.$modal.msgSuccess(row.black ? "取消拉黑成功！" : "拉黑成功！");
            row.black = !row.black;
          });
        }).catch(() => {
      });
    },
    // 已发货提交
    handleSubmit() {
      submitOrder(this.ids).then((response) => {
        this.$modal.msgSuccess("提交成功！");
        this.getList();
      });
    },
    // 完成所有操作
    handleFinish() {
      this.$modal.confirm('是否确认订单已经完成？点击之后，本系统不再处理这批订单！')
        .then(() => {
          finishOrder(this.ids).then((response) => {
            this.$modal.msgSuccess("完结订单成功！");
            this.getList();
          });
        }).catch(() => {
      });
    },
    //处理缺货
    handleOut(row) {
      if (!this.single) {
        //单个缺货同时备注
        this.reset();
        const orderSn = row.orderSn || this.ids;
        getOrder(orderSn).then((response) => {
          this.form = response.data;
          this.form.sysStatus = 4;
          this.open = true;
          this.title = "添加备注";
          this.isOut = true;
        });
      } else {
        outsOrder(this.ids).then((response) => {
          this.$modal.msgSuccess("标注缺货成功!");
          this.getList();
        });
      }
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.isOut) {
            //处理缺货
            outOrder(this.form).then((response) => {
              this.$modal.msgSuccess("标记缺货成功！");
              this.open = false;
              this.getList();
            });
          } else {
            //处理备注
            remarkOrder(this.form).then((response) => {
              this.$modal.msgSuccess("备注成功！");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /////////////////上面是请求数据//   下面是页面方法/////////////////
    //行点击方法
    handleRowAction(event, row) {
      this.contextMenuRow = event;
    },
    //右键方法
    showContextMenu(event, row) {
      this.contextMenuPosition = {x: event.clientX, y: event.clientY};
      this.isContextMenuVisible = true;
      document.addEventListener('click', this.closeContextMenuOnClick);
    },
    closeContextMenuOnClick(event) {
      // 获取上下文菜单的 DOM 元素
      const contextMenuElement = this.$refs.contextMenu.$el;
      // 如果点击事件的目标不在上下文菜单内，则关闭上下文菜单
      if (!contextMenuElement.contains(event.target)) {
        this.isContextMenuVisible = false;
        // 移除全局点击事件监听器
        document.removeEventListener('click', this.closeContextMenuOnClick);
      }
    },
    handleContextMenuAction(action, row) {
      if (action === 'urgent') {
        //  处理加急操作
        this.handleUrgent(row);
      } else if (action === 'remark') {
        this.handleNote(row);
      } else if (action === 'black') {
        this.handleBlack(row);
      }
      this.isContextMenuVisible = false;
      // 移除全局点击事件监听器
      document.removeEventListener('click', this.closeContextMenuOnClick);
    },


    //点击行触发，选中或不选中复选框
    handleRowClick(row) {
      this.$refs.dataTable.toggleRowSelection(row);
    },
    //行高亮
    highlightRow({row, index}) {
      return this.ids.includes(row.orderSn) ? "current-row" : "";
    },
    // 计算剩余发货天数
    formatTimeDifference(targetDate) {
      const targetTime = new Date(targetDate);
      const currentTime = new Date();
      // 计算时间差（以毫秒为单位）
      const timeDifference = targetTime - currentTime;
      // 计算剩余的天数和小时数
      let days = 0;
      if (timeDifference >= 0) {
        days = Math.floor(timeDifference / (1000 * 60 * 60 * 24));
      } else {
        days = Math.ceil(timeDifference / (1000 * 60 * 60 * 24));
      }
      const hours = Math.floor((timeDifference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
      return `${days}天 ${hours}小时`;
    },
    // 计算属性用于判断紧急
    isIn48Hours(someDate) {
      const targetTime = new Date(someDate);
      const currentTime = new Date();
      return targetTime - currentTime < (1000 * 60 * 60 * 24 * 2);
    },
    //获取中文状态文字
    getOrderStatusText(status) {
      return this.statusOptions[status];
    },
  },
};
</script>
<style lang="scss" scoped>
@import '@/assets/styles/variables.scss';


.order-contain {
  ul {
    padding: 0px;
    margin-top: 1px;
    margin-bottom: 1px;

    li {
      margin-top: 0px;
    }
  }
}

.order-top {
  height: 50px;
  background-color: white;
  border-top-left-radius: 10px; /* 左上角圆滑程度，根据需要调整像素值 */
  border-top-right-radius: 10px; /* 右上角圆滑程度，根据需要调整像素值 */
  box-shadow: 0px 5px 10px 0px rgba(170, 195, 200, 0.5);
  margin-bottom: 0px;
  padding: 0 30px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-top-fixed {
  position: fixed;
  top: 0;
  z-index: 800; /* 确保它在其他内容上层显示 */
}

.order-number-contain {
  .order-number {
    color: $themeSubColor;
    font-weight: 500;
    font-size: 18px;
  }

  .order-number-notice {
    font-size: 18px;
    font-weight: 500;
    color: #000000;
  }
}

.item-cell-li {
  overflow: hidden; /* 用于清除浮动 */
}

.item-image {
  width: 75px;
  height: 75px;
  float: left; /* 图片浮动到左侧 */
  margin-right: 10px; /* 为图 片留出一些间距 */
}

.item-cell-li p {
  margin: 0px;
  text-align: left;
  white-space: nowrap; /* 阻止文字自动换行 */
  //font-size: 12px;
}

/* 分隔线样式 */
.item-cell-li + .item-cell-li {
  border-top: 1px dashed #d7d7d7; /* 添加短虚线分隔线 */
  margin-top: 5px; /* 控制分隔线的间距 */
  padding-top: 5px; /* 控制分隔线的间距 */
}

.user-cell p {
  margin-bottom: 2px;
  margin-top: 2px;
}

.time-cell p {
  margin-bottom: 1px;
  margin-top: 1px;
  font-size: 12px;
}

.text-bold {
  font-weight: bold;
}

.text-highlight {
  color: $themeSubColor; /* 或者你想要的红色值 */
  font-size: 18px;
  font-weight: bold;
}

</style>
